/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86187
 * Date: 2022-10-16
 * Time: 0:22
 */
public class Solution {
    public static String ReverseSentence(String str) {
        if(str == null || str.length() <= 1)
            return str;

        // 1.逆置每个单词.
        char[] s = str.toCharArray();
        int length = s.length;
        int i = 0;
        int j = i;
        while(i < length) {
            while(i < length && s[i] != ' ')
                // 找空格
                ++i;
            reverseString(s,j,i-1);
            // 防止有多个空格
            while (i < length && s[i] == ' ')
                ++i;
            j = i;
        }
            //有多个但此时逆置最后一个单词, 只有一个单词时就是逆置该单词.
        reverseString(s,j,i-1);
        // 2. 整体逆置
        reverseString(s,0,length-1);

        return new String(s);
    }
    private static void reverseString(char[] ch, int start, int end) {
        while(start < end) {
            char tmp = ch[start];
            ch[start] = ch[end];
            ch[end] = tmp;
            start++;
            end--;
        }
    }

    public static void main(String[] args) {
        String str = "student. a am I";
        System.out.println(ReverseSentence(str));
    }
}
